package com.gzhryc.shared_device.oem.code.business.services;

import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.oem.code.business.dao.CouponActivityPlaceDao;
import com.gzhryc.shared_device.oem.code.business.dao.db.CouponActivity;
import com.gzhryc.shared_device.oem.code.business.dao.db.CouponActivityPlace;
import com.gzhryc.shared_device.oem.code.business.dao.enums.CouponActivityEnum;
import com.gzhryc.shared_device.oem.code.business.dao.enums.CouponActivityPlaceEnum;
import com.gzhryc.shared_device.oem.code.business.services.dto.CouponActivityPlaceSearch;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class CouponActivityPlaceService {

    static Logger log = Logger.getLogger(CouponActivityPlaceService.class);

    public static CouponActivityPlaceService self() {
        return MultiDBTools.getService(CouponActivityPlaceService.class, true);
    }

    public static CouponActivityPlaceService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, CouponActivityPlaceService.class, true);
    }

    CouponActivityPlaceDao dao;

    public CouponActivityPlaceService(String jdbcKey) {
        this.dao = new CouponActivityPlaceDao(jdbcKey);
    }

    public List<CouponActivityPlace> findJoinByActivityId(Long activityId,Integer pageNo,Integer pageLimit){
        if(activityId != null){
            Conditions conditions = new Conditions(CouponActivityPlace.class);
            conditions.and().is("activityId",activityId);

            try {
                return dao.findJoinByCondition(conditions,pageNo,pageLimit);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public List<CouponActivityPlace> findJoinBySearch(CouponActivityPlaceSearch search){
        Conditions conditions = dao.buildConditions(search);
        if(search.getCouponActivity() != null) {
            conditions.and().is("couponActivity.type",search.getCouponActivity().getType());
            conditions.and().is("couponActivity.user_id", search.getCouponActivity().getUserId());
            conditions.and().is("couponActivity.coupon_type", search.getCouponActivity().getCouponType());
            conditions.and().is("couponActivity.business_type", search.getCouponActivity().getBusinessType());
            conditions.and().is("couponActivity.use_limit", search.getCouponActivity().getUseLimit());
            conditions.and().is("couponActivity.use_range", search.getCouponActivity().getUseRange());
            conditions.and().is("couponActivity.state", search.getCouponActivity().getState());
        }
        try {
            return dao.findJoinByCondition(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countJoinByActivityId(Long activityId){
        if(activityId != null) {
            Conditions conditions = new Conditions(CouponActivityPlace.class);
            conditions.and().is("activityId", activityId);

            try {
                return dao.countJoin(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return 0L;
    }

    public CouponActivityPlace getByKeys(Long activityId,Long placeId){
        if(activityId != null && placeId != null){
            Conditions conditions = new Conditions(CouponActivityPlace.class);
            conditions.and().is("activityId",activityId);
            conditions.and().is("placeId",placeId);

            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public boolean addPlaceIds(Long activityId,String[] placeIds) throws LogicException {
        if(activityId != null && placeIds != null && placeIds.length > 0){
            CouponActivity couponActivity = CouponActivityService.self().getJoinById(activityId);
            if(couponActivity == null){
                throw new LogicException("未找到优惠活动");
            }

            if(CouponActivityEnum.Type.NewPeople.index().equals(couponActivity.getType())){
                throw new LogicException("新人领取优惠活动不允许设置网点");
            }

            JdbcSession.begin();
            try {
                boolean flag = CouponActivityEnum.UseRange.DesignatedPlace.index().equals(couponActivity.getUseRange());
                if(!flag){
                    flag = CouponActivityService.self().updateUseRange(couponActivity.getId(),CouponActivityEnum.UseRange.DesignatedPlace.index());
                }

                if(flag) {
                    for (String str : placeIds) {
                        Long placeId = Long.valueOf(str);
                        CouponActivityPlace activityPlace = getByKeys(activityId, placeId);
                        if (activityPlace != null) {
                            if (CouponActivityPlaceEnum.State.Disable.index().equals(activityPlace.getState())) {
                                Conditions conditions = new Conditions(CouponActivityPlace.class);
                                conditions.and().is("activityId", activityId);
                                conditions.and().is("placeId", placeId);

                                CouponActivityPlace updateEntity = new CouponActivityPlace();
                                updateEntity.setState(CouponActivityPlaceEnum.State.Enable.index());

                                flag = dao.updateNotNull(updateEntity, conditions) > 0;
                            }
                        } else {
                            activityPlace = new CouponActivityPlace();
                            activityPlace.setActivityId(activityId);
                            activityPlace.setPlaceId(placeId);
                            activityPlace.setCouponCount(0);
                            activityPlace.setState(CouponActivityPlaceEnum.State.Enable.index());
                            activityPlace.setCreateDate(new Date());

                            flag = dao.insert(activityPlace) > 0;
                        }

                        if (!flag) {
                            break;
                        }
                    }

                    if (flag) {
                        JdbcSession.commit();
                        return true;
                    }
                }
            }catch (SQLException e){
                log.error(e.getMessage(),e);
            }finally {
                JdbcSession.end();
            }
        }
        return false;
    }

    public boolean updateState(Long activityId,Long placeId,Integer state)throws LogicException{
        if(activityId != null && placeId != null && state != null){
            Conditions conditions = new Conditions(CouponActivityPlace.class);
            conditions.and().is("activityId",activityId);
            conditions.and().is("placeId",placeId);

            CouponActivityPlace updateEntity = new CouponActivityPlace();
            updateEntity.setState(state);

            try {
                return dao.updateNotNull(updateEntity,conditions) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean addCouponCount(Long activityId,Long placeId){
        if(activityId != null && placeId != null){
            Conditions conditions = new Conditions(CouponActivityPlace.class);
            conditions.and().is("activityId",activityId);
            conditions.and().is("placeId",placeId);

            CouponActivityPlace updateEntity = new CouponActivityPlace();
            updateEntity.setCouponCount(1);

            try {
                return dao.updateNotNullAndInc(updateEntity,conditions,"couponCount") > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean deleteByActivityId(Long activityId){
        if(activityId != null){
            Conditions conditions = new Conditions(CouponActivityPlace.class);
            conditions.and().is("activityId",activityId);

            try {
                return dao.deleteByCondition(conditions) >= 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean deleteByKeys(Long activityId,Long placeId) throws LogicException{
        if(activityId != null && placeId != null){
            Conditions conditions = new Conditions(CouponActivityPlace.class);
            conditions.and().is("activityId",activityId);
            conditions.and().is("placeId",placeId);

            JdbcSession.begin();
            try {
                if(dao.deleteByCondition(conditions) > 0){
                    Long total = countJoinByActivityId(activityId);
                    if(total == null || total <= 0){
                        if(CouponActivityService.self().updateUseRange(activityId,CouponActivityEnum.UseRange.Unlimited.index())){
                            JdbcSession.commit();
                            return true;
                        }
                    }else{
                        JdbcSession.commit();
                        return true;
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }finally {
                JdbcSession.end();
            }
        }
        return false;
    }
}
